package com.baoer.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.crypto.SecretKey;
import java.util.Map;


@Configuration
public class JwtUtil {

    @Autowired
    private RedisUtil redisUtil;

    private String signKey = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";


        public String generateJWT(Map<String, Object> claims) {
        SecretKey key = Keys.hmacShaKeyFor(signKey.getBytes());
        return Jwts.builder()
                .claims(claims)
                .signWith(key)
                .compact();
    }

    public Map<String, Object> parseJWT(String jwt) {
        SecretKey key = Keys.hmacShaKeyFor(signKey.getBytes());
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(jwt)
                .getPayload();
    }

    //    验证token是否正确
    public boolean isTrue(String token) {
        Object key = redisUtil.getKey(token.substring(token.lastIndexOf(".") + 1));
        return key != null;
    }

    //    验证token是否过期
    public boolean verityToken(String token) {
        String tokenKey = token.substring(token.lastIndexOf(".") + 1);
        boolean flag = redisUtil.containsKey(tokenKey);
        if (flag) {
            redisUtil.setExKey(tokenKey, token, 3600L);
            return true;
        }
        return false;
    }

    //    token放到redis里
    public String putToken(Map<String, Object> claims) {
        String token = generateJWT(claims);
        String tokenKey = token.substring(token.lastIndexOf(".") + 1);
        redisUtil.setExKey(tokenKey, token, 3600L);
        return token;
    }

}
